import React, { useEffect } from 'react';

interface ILabelledValue {
    label: string;
}

interface ISquareConfig {
    color?: string;
    width?: number;
    [propName: string]: any
}

interface ISquareResult {
    color: string;
    area: number;
}

interface IPoint {
    readonly x: number;
    readonly y: number;
    z: number;
}

type ISearchFunc  = (source: string, subSource: string) => boolean

interface IStringArray {
    [index: number]: string;
}

interface IStrMap {
    [str: string]: string
}

interface IDoubleMap {
    [str: string]: any,
    [index: number]: string
}

interface IReadonlyString {
    readonly [index: number]: string
}
const OtherInterface = () => {

    const printLabel = (labelObj: ILabelledValue): void => {
        console.log(labelObj.label)
    }

    const initSquare = (config: ISquareConfig): ISquareResult => {
        const newSquare = {color: 'white', area: 100};
        if(config.color){
            newSquare.color = config.color;
        }
        if(config.width){
            newSquare.area = config.width * config.width;
        }

        return newSquare;
    }

    const testReadOnly = () => {
        const p1: IPoint = {x: 1, y: 1, z: 1}
        p1.z = 2
        console.log(p1)
        let a: number[] = [1,2,3,4]
        const ro: ReadonlyArray<number> = a;
        a = ro as number[]
        console.log(ro)
    }

    const mySearch: ISearchFunc  = (src: string, sub: string): boolean => {
        const result = src.search(sub)
        return result > -1
    }

    const testStr = () => {
        const stringArray: IStringArray = ["Bob", "Fred"];
        const myStr: string = stringArray[0];
        console.log(myStr)
        // const numMap: IStringArray = {
        //     1: 'foo',
        //     2: 'bar',
        //     '3': 'why',
        //     'c': 'c;c' // 报错：“'c'”不在类型“IStringArray”
        // }
        const obj: IStrMap = {
            bar: 'bar',
            foo: 'foo',
            1: 'kk' // 可正常编译
        }
        console.log(obj[1])
        // 类型“string[]”中缺少索引签名。
        // const obj1: IStrMap = ['foo', 'bar']
        const objDouble: IDoubleMap = ['foo', 'bar']
        console.log(objDouble)

        const RLArray: IReadonlyString = ['foo', 'bar']
        console.log(RLArray)
        // RLArray[1] = 'kk'// 报错：类型“IReadonlyString”中的索引签名仅允许读取。
    }

    useEffect(() => {
        const labelObj = {label: 'like', size: 10}
        printLabel(labelObj)
        const square = initSquare({color: 'black', width: 9, opacity: 0.2})
        console.log(square)
        testReadOnly()
        console.log(mySearch('abc', 'c'))
        testStr()
    }, [])

    return <div>interface</div>
}

export default OtherInterface;